<template>
  <div>
    <a-card title="流程定义列表" :loading="loading">
      <a-table :columns="columns" :data-source="definitions" row-key="id" size="small" :pagination="false">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'actions'">
            <a-space>
              <a-button type="primary" size="small" @click="openStart(record)">启动</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    <a-modal v-model:open="startVisible" title="启动流程" @ok="doStart" :confirm-loading="starting">
      <a-form layout="vertical">
        <a-form-item label="流程定义 Key">
          <a-input v-model:value="form.definitionKey" disabled />
        </a-form-item>
        <a-form-item label="Business Key (可选)">
          <a-input v-model:value="form.businessKey" placeholder="例如 LEAVE-2024-001" />
        </a-form-item>
        <a-form-item label="变量 JSON (可选)">
          <a-textarea v-model:value="form.variablesJson" placeholder='{"applicantId":"EMP001","leaveHours":8}' rows="4" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { listDefinitions, startProcess } from '../services/flowable';

const loading = ref(false);
const definitions = ref<any[]>([]);

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id' },
  { title: 'Key', dataIndex: 'key', key: 'key' },
  { title: '名称', dataIndex: 'name', key: 'name' },
  { title: '版本', dataIndex: 'version', key: 'version' },
  { title: '操作', key: 'actions' }
];

const startVisible = ref(false);
const starting = ref(false);
const form = ref({ definitionKey: '', businessKey: '', variablesJson: '' });

function openStart(def: any) {
  form.value = { definitionKey: def.key, businessKey: '', variablesJson: '' };
  startVisible.value = true;
}

async function doStart() {
  starting.value = true;
  try {
    let vars: Record<string, any> | undefined = undefined;
    if (form.value.variablesJson.trim()) {
      try { vars = JSON.parse(form.value.variablesJson); } catch { message.error('变量 JSON 解析失败'); starting.value = false; return; }
    }
    const res = await startProcess(form.value.definitionKey, form.value.businessKey || undefined, vars);
    message.success('启动成功: ' + res.id);
    startVisible.value = false;
  } catch (e:any) {
    message.error(e.message || '启动失败');
  } finally {
    starting.value = false;
  }
}

async function load() {
  loading.value = true;
  try {
    definitions.value = await listDefinitions();
  } catch (e:any) {
    message.error(e.message || '加载失败');
  } finally {
    loading.value = false;
  }
}

onMounted(load);
</script>
